package com.mm.mweather.fragments

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import com.mm.mweather.MainActivity

import com.mm.mweather.R
import com.mm.mweather.WeatherActivity
import com.mm.mweather.db.City
import com.mm.mweather.db.Country
import com.mm.mweather.db.Province
import com.mm.mweather.util.HttpUtil
import com.mm.mweather.util.Utility
import kotlinx.android.synthetic.main.activity_weather.*

import org.litepal.crud.DataSupport

import java.io.IOException
import java.util.ArrayList

import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response

class ChooseFragment : Fragment() {
    private var progressDialog: ProgressDialog? = null
    private var titleText: TextView? = null
    private var backButton: Button? = null
    private var listView: ListView? = null
    private var adapter: ArrayAdapter<String>? = null
    private val datalist = ArrayList<String>()

    //省级列表
    private var provinceList: List<Province>? = null

    //市级列表
    private var cityList: List<City>? = null

    //县列表
    private var countryList: List<Country>? = null

    //选中的省份
    private var selectProvince: Province? = null

    //选中城市
    private var selectCity: City? = null

    //当前选中的级别
    private var currentLevel: Int = 0

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.choose_area, container, false)
        titleText = view.findViewById<View>(R.id.title_text) as TextView
        backButton = view.findViewById<View>(R.id.back_button) as Button
        listView = view.findViewById<View>(R.id.list_view) as ListView
        adapter = ArrayAdapter(context!!, android.R.layout.simple_list_item_1, datalist)
        listView!!.adapter = adapter
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        listView!!.setOnItemClickListener { parent, view, position, id ->
            if (currentLevel == LBVBL_PROVICB) {
                selectProvince = provinceList!![position]
                queryCities()
            } else if (currentLevel == LBVBL_CITY) {
                selectCity = cityList!![position]
                queryCountries()
            }else if (currentLevel== LBVBL_COUNTRY){
                var weatherId: String = countryList!![position].weatherId
                if ( activity is MainActivity) {
                    var mainActivity:MainActivity=activity as MainActivity
                    mainActivity.drawerLayout!!.closeDrawers()
                    mainActivity.swipe_refresh.isRefreshing=true
                    mainActivity.resquestWeather(weatherId)
                    mainActivity.resquestapi(weatherId)
                }
            }
        }
        backButton!!.setOnClickListener { v ->
            if (currentLevel == LBVBL_COUNTRY) {
                queryCities()
            } else if (currentLevel == LBVBL_CITY) {
                queryProvinces()
            }
        }
        queryProvinces()
    }

    /*
    查询全国所有的省
     */
    private fun queryProvinces() {
        titleText!!.text = "中国"
        backButton!!.visibility = View.GONE
        provinceList = DataSupport.findAll(Province::class.java)
        if (provinceList!!.size > 0) {
            datalist.clear()
            for (province in provinceList!!) {
                datalist.add(province.provinceName)

            }
            adapter!!.notifyDataSetChanged()
            listView!!.setSelection(0)
            currentLevel = LBVBL_PROVICB
        } else {
            val address = "http://guolin.tech/api/china"
            queryFromServer(address, "province")
        }
    }

    /*
   查询选中省内的所有城市
    */
    private fun queryCities() {
        titleText!!.text = selectProvince!!.provinceName
        backButton!!.visibility = View.VISIBLE
        cityList = DataSupport.where("provinceId=?", selectProvince!!.id.toString()).find(City::class.java)
        if (cityList!!.size > 0) {
            datalist.clear()
            for (city in cityList!!) {
                datalist.add(city.cityName)
            }
            adapter!!.notifyDataSetChanged()
            listView!!.setSelection(0)
            currentLevel = LBVBL_CITY
        } else {
            val provinceCode = selectProvince!!.provinceCode
            val address = "http://guolin.tech/api/china/$provinceCode"
            queryFromServer(address, "city")
        }
    }

    /*
  查询选中城市的所有县
   */
    private fun queryCountries() {
        titleText!!.text = selectCity!!.cityName
        backButton!!.visibility = View.VISIBLE
        countryList = DataSupport.where("cityId=?", selectCity!!.id.toString()).find(Country::class.java)
        if (countryList!!.size > 0) {
            datalist.clear()
            for (country in countryList!!) {
                datalist.add(country.countryName)
            }
            adapter!!.notifyDataSetChanged()
            listView!!.setSelection(0)
            currentLevel = LBVBL_COUNTRY
        } else {
            val provinceCode = selectProvince!!.provinceCode
            val countryCode = selectCity!!.cityCode
            val address = "http://guolin.tech/api/china/$provinceCode/$countryCode"
            queryFromServer(address, "country")
        }
    }

    /*
    从服务器查询数据
     */
    private fun queryFromServer(address: String, type: String) {
        showProgressDialog()
        HttpUtil.sendOkHttpRequests(address, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                activity!!.runOnUiThread {
                    closeProgressDialog()
                    Toast.makeText(context, "加载失败", Toast.LENGTH_SHORT).show()
                }
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                val resposeText = response.body()!!.string()
                var result = false
                if ("province" == type) {
                    result = Utility.handleProvinceResponse(resposeText)
                } else if ("city" == type) {
                    result = Utility.handleCityResponse(resposeText, selectProvince!!.id)
                } else if ("country" == type) {
                    result = Utility.handleCountryResponse(resposeText, selectCity!!.id)
                }
                if (result) {
                    activity!!.runOnUiThread {
                        closeProgressDialog()
                        if ("province" == type) {
                            queryProvinces()
                        } else if ("city" == type) {
                            queryCities()
                        } else if ("country" == type) {
                            queryCountries()
                        }
                    }
                }
            }
        })
    }

    private fun showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = ProgressDialog(activity)
            progressDialog!!.setMessage("正在加载....")
            progressDialog!!.setCanceledOnTouchOutside(false)
        }
        progressDialog!!.show()
    }

    private fun closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog!!.dismiss()
        }
    }

    companion object {
        val LBVBL_PROVICB = 0
        val LBVBL_CITY = 1
        val LBVBL_COUNTRY = 2
    }
}
